<template>
  <!-- 组织 -->
  <el-dialog v-model="dialogVisible" width="800px" @close="close">
    <template #default>
      <el-form :model="userForm" label-width="120px" class="user-editor-form">
        <el-form-item label="组织编码" prop="code" v-if="unitUpdateId" class="inline">
          <span class="el-input__inner">{{ userForm.code }}</span>
        </el-form-item>
        <el-form-item label="组织层级编码" prop="codeseq" v-if="unitUpdateId" class="inline">
          <span class="el-input__inner">{{ userForm.codeseq }}</span>
        </el-form-item>
        <el-form-item label="组织名称" prop="name" class="inline">
          <el-input v-model="userForm.name" show-word-limit placeholder="请输入组织名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contact" class="inline">
          <el-input v-model="userForm.contact" show-word-limit placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系方式" prop="mobile" class="inline">
          <el-input v-model="userForm.mobile" show-word-limit placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="地址" prop="address" class="inline">
          <el-input v-model="userForm.address" show-word-limit placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email" class="inline">
          <el-input v-model="userForm.email" show-word-limit placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="网址" prop="web" class="inline">
          <el-input v-model="userForm.web" show-word-limit placeholder="请输入网址" />
        </el-form-item>

        <el-form-item label="是否有下级组织" prop="hasChildren" v-if="unitUpdateId" class="inline">
          <el-radio-group v-model="userForm.hasChildren">
            <el-radio
              v-for="item in dicts.system_global_status"
              :key="item.v"
              :label="userForm.hasChildren == item.v ? userForm.hasChildren : item.v"
              :value="item.v"
            >
              {{ item.k }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="unitUpdateId"
          style="visibility: hidden"
          label=""
          prop="parentId"
          class="inline"
        >
        </el-form-item>
        <el-form-item label="上级组织" prop="parentId" class="inline">
          <el-tree
            ref="menuTreeRef"
            :data="permission.treeList"
            :props="permission.treeProps"
            check-strictly="true"
            show-checkbox
            node-key="id"
            class="tree"
            :default-expanded-keys="defaultExpand"
            @check="toggleTreeChecked"
          >
          </el-tree>
        </el-form-item>
        <!-- <el-form-item label="负责人" prop="leaderId" class="inline">
          <el-input v-model="userForm.leaderId" placeholder="请输入邮箱" />
        </el-form-item> -->
      </el-form>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import {
  ref,
  reactive,
  onBeforeMount,
  toRefs,
  getCurrentInstance,
  ComponentInternalInstance
} from 'vue'
import { ElTree } from 'element-plus'

import { organizationTree, unitAdd, unitGet, unitUpdate } from '@api/systemUnit'
import { ElMessage } from 'element-plus'
import { Organization } from '@interface/systemUnit'

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  unitUpdateId: {
    type: String,
    default: ''
  }
})

const dialogVisible = ref(props.dialogVisible)
const unitUpdateId = ref(props.unitUpdateId)
const defaultExpand = ref<number[]>([])
const menuTreeRef = ref<InstanceType<typeof ElTree>>()
const state = reactive({
  userForm: {
    id: '',
    name: '',
    code: '',
    codeseq: '',
    contact: '',
    address: '',
    email: '',
    web: '',
    parentId: '',
    hasChildren: '0'
    // isSystem: false,
    // enabled: false
    // leaderId: false
  },
  dicts: {}
})

const { userForm } = toRefs(state)

const permission = reactive({
  treeList: [] as unknown as Organization,
  treeProps: {
    label: 'name'
  }
})

onBeforeMount(async () => {
  const { proxy } = getCurrentInstance() as ComponentInternalInstance
  if (proxy) {
    ;(proxy as any).getDicts(['system_global_status', 'system_global_gender'])
  }
  getOrganizationMenuTree()
  editFeedback()
})

//获取组织树
const getOrganizationMenuTree = async () => {
  const Tree = await organizationTree()
  console.log(Tree)
  const { data } = Tree
  permission.treeList = data
}
//提交
const onSubmit = async () => {
  const parentIdInfo = menuTreeRef.value!.getCheckedKeys() as string[]
  const [parentId] = parentIdInfo
  userForm.value.parentId = parentId
  if (unitUpdateId.value !== '') {
    const res = await unitUpdate({ ...userForm.value })
    if (res.code != '200') {
      ElMessage({
        type: 'error',
        message: res.message
      })
    } else {
      ElMessage({
        type: 'success',
        message: '操作成功'
      })
    }
  } else {
    const res = await unitAdd({ ...userForm.value })
    if (res.code != '200') {
      ElMessage({
        type: 'error',
        message: res.message
      })
    } else {
      ElMessage({
        type: 'success',
        message: '操作成功'
      })
    }
  }

  emit('update:dialogVisible', false)
  emit('getUnit')
}
const toggleTreeChecked = (data, checkObj) => {
  // 共两个参数，依次为：传递给 data 属性的数组中该节点所对应的对象、树目前的选中状态对象
  // 树目前的选中状态对象，包含 checkedNodes、checkedKeys、halfCheckedNodes、halfCheckedKeys 四个属性
  if (checkObj.checkedKeys.length != 0) {
    if (checkObj.checkedKeys.length == 2) {
      // 如果选择超过一个节点，则只保留最后一个节点
      //单选实现
      menuTreeRef.value!.setCheckedKeys([data.id])
    }
  }
}

// 编辑回显
const editFeedback = async () => {
  if (unitUpdateId.value !== '') {
    const result = await unitGet(unitUpdateId.value)
    const { data } = result
    Object.assign(userForm.value, data)
    userForm.value.hasChildren = userForm.value.hasChildren ? '1' : '0'
    menuTreeRef.value!.setCheckedKeys([data.parentId])
    defaultExpand.value = [Number(data.parentId)]
  }
}

// eslint-disable-next-line vue/valid-define-emits
const emit = defineEmits()
//弹窗关闭
const close = () => {
  emit('unitChange')
  emit('update:dialogVisible', false)
}
</script>

<style lang="scss" scoped>
.user-editor-form {
  :deep(.inline) {
    display: inline-flex;
    vertical-align: middle;
    width: 50%;
  }

  .treeList {
    padding: 2px;
    width: 100%;
  }
}
.inline {
  display: inline-flex;
  vertical-align: middle;
  width: 50%;
}
.tree {
  // margin-top: 0.5rem;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 0.5rem;
  padding: 5px;
  flex: 1;
  height: 20vh;
  overflow: auto;
}
</style>
